package org.benjamin.lending.controller;

import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.search.aggregator.Sum;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.TransactRequest;
import org.benjamin.lending.repository.TransactRequestRepository;
import org.benjamin.lending.service.TransactService;
import org.benjamin.lending.service.impl.SumapayTransactServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

public class SumapayResponseInterceptor extends HandlerInterceptorAdapter {

	private Logger logger = LogManager.getLogger();

	@Autowired
	private TransactRequestRepository transactRequestRepository;

	@Autowired
	private TransactService transactService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Map<String, Object> responseMap = WebUtils.getParametersStartingWith(request, "");
		logger.debug("服务器接受到的数据是：{}",responseMap);
		String requestId = responseMap.get("requestId").toString();
		TransactRequest transactRequest = this.transactRequestRepository.findOne(requestId);
		String[] signatureKeyArray = null;
		logger.info("当前拦截器进行对丰付的参数校验");
		switch (transactRequest.getType()) {
		case RECHARGE:
			logger.debug("当前数据加密采用【充值加密】");
			signatureKeyArray = SumapayTransactServiceImpl.RESPONES_USER_RECHARGE;
			break;
		case REGISTER_USER:
			logger.debug("【账户开户签名】");
			signatureKeyArray = SumapayTransactServiceImpl.RESPONSE_REGISTER_USER;
			break;
		case WITHDRAW:
			logger.debug("校验提现签名");
			signatureKeyArray = SumapayTransactServiceImpl.RESPONSE_WITHDRAW;
			break;
		default:
			break;
		}
		boolean result = this.transactService.checkTheSignature(responseMap, signatureKeyArray);
		if (result) {
			logger.info("数字签名校验通过");
			return true;
		}
		logger.info("数据校验未通过：接受参数：{}", responseMap);
		return false;
	}

}
